package com.lzy.business.facade;

import com.github.pagehelper.PageInfo;
import com.lzy.business.request.AgentcashBackRecordRequest;
import com.lzy.business.response.AgentContractReponse;
import com.lzy.business.response.AgentOrderInfoReponse;
import com.lzy.business.response.AgentProtocolAccountDtoResponse;
import com.lzy.business.response.AgentcashBackRecordResponse;
import com.lzy.coupon.apis.MotorcycleServiceApi;
import com.lzy.coupon.apis.MotorcycleSpecServiceApi;
import com.lzy.coupon.dtos.MotorcycleDto;
import com.lzy.coupon.dtos.MotorcycleSpecDto;
import com.lzy.framework.core.datasource.multiple.DataSource;
import com.lzy.framework.core.datasource.multiple.DataSourceHolder;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.member.apis.MemberUserServiceApi;
import com.lzy.member.dtos.MemberUserDto;
import com.lzy.product.apis.*;
import com.lzy.product.constants.AgentOrderEnum;
import com.lzy.product.constants.BusinessType;
import com.lzy.product.dtos.*;
import com.lzy.product.dtos.agent.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Component
public class AgentOrderInfoFacade {

    @Autowired
    private AgentOrderInfoServiceApi agentOrderInfoServiceApi;

    @Autowired
    private AgentProtocolServiceApi agentProtocolServiceApi;

    @Autowired
    private ProductUserServiceApi productUserServiceApi;

    @Autowired
    private AgentProductServiceApi agentProductServiceApi;

    @Autowired
    private AgentOrderYieldRatioServiceApi agentOrderYieldRatioServiceApi;

    @Autowired
    private CouponProfitRecordServiceApi couponProfitRecordServiceApi;

    @Autowired
    private MemberCouponsServiceApi memberCouponsServiceApi;

    @Autowired
    private MemberUserServiceApi memberUserServiceApi;

    @Autowired
    private AgentProductProjectServiceApi agentProductProjectServiceApi;

    @Autowired
    private MotorcycleSpecServiceApi motorcycleSpecServiceApi;

    @Autowired
    private MotorcycleServiceApi motorcycleServiceApi;

    @Autowired
    private AgentOrderProjectRecordServiceApi agentOrderProjectRecordServiceApi;

    @Autowired
    private ProjectServiceApi projectServiceApi;

    /**
     * 根据订单号查询
     *
     * @param orderId
     * @return
     */
    public AgentOrderInfoReponse queryOrderById(Long orderId) {
        AgentOrderInfoReponse agentOrderInfoReponse = new AgentOrderInfoReponse();
        AgentOrderInfoDto agentOrderInfoDto = agentOrderInfoServiceApi.queryOrderById(orderId);
        Ensure.that(agentOrderInfoDto).isNotNull("01001615");
        ProductUserDto productUserDto = productUserServiceApi.findById(agentOrderInfoDto.getUserId());
        if (productUserDto != null) {
            agentOrderInfoDto.setShopName(productUserDto.getName());
            agentOrderInfoDto.setShopPhone(productUserDto.getPhone());
        }
        if (agentOrderInfoDto.getType().equals(AgentOrderEnum.OrderType.AgentProduct.getCode())) {
            AgentProductDto agentProductDto = agentProductServiceApi.queryAgentProductById(agentOrderInfoDto.getSourceId());
            agentOrderInfoDto.setProductUrl(agentProductDto.getCover());
            agentOrderInfoDto.setProductName(agentProductDto.getName());
            agentOrderInfoDto.setProductPrice(agentProductDto.getPrice());
        }
        agentOrderInfoReponse.setAgentOrderInfoDto(agentOrderInfoDto);
        if (agentOrderInfoDto.getType().equals(AgentOrderEnum.OrderType.AgentAgreement.getCode())) {
            agentOrderInfoReponse.setAgentProtocolDto(agentProtocolServiceApi.findById(agentOrderInfoDto.getSourceId()));
        }
        return agentOrderInfoReponse;
    }


    public PageInfo cashBackRecord(AgentcashBackRecordRequest agentcashBackRecordRequest) {
        List<AgentcashBackRecordResponse> list = new ArrayList<>();
        AgentOrderInfoDto agentOrderInfoDto = agentOrderInfoServiceApi.findByOrderId(agentcashBackRecordRequest.getOrderId());
        Ensure.that(agentOrderInfoDto).isNotNull("01001615");
        Long sourceId = agentOrderInfoDto.getSourceId();
        AgentOrderYieldRatioDto agentOrderYieldRatioDto = new AgentOrderYieldRatioDto();
        agentOrderYieldRatioDto.setType(2);
        agentOrderYieldRatioDto.setSourceId(sourceId);
        agentOrderYieldRatioDto.setOrderId(agentcashBackRecordRequest.getOrderId());
        List<AgentOrderYieldRatioDto> agentOrderYieldRatioDtos = agentOrderYieldRatioServiceApi.query(agentOrderYieldRatioDto);
        if (agentOrderYieldRatioDtos.size() == 0) {
            return new PageInfo();
        }
        agentOrderYieldRatioDto = agentOrderYieldRatioDtos.get(0);
        AgentProtocolDto agentProtocolDto = agentProtocolServiceApi.selectDetailById(agentOrderInfoDto.getSourceId());
        Pager pager = new Pager();
        pager.setPageSize(agentcashBackRecordRequest.getPageSize());
        pager.setPageNum(agentcashBackRecordRequest.getPageNum());
        CouponProfitRecordDto couponProfitRecordDto = new CouponProfitRecordDto();
        couponProfitRecordDto.setOrderId(agentOrderInfoDto.getOrderId());
        couponProfitRecordDto.setType(4);
        couponProfitRecordDto.setStartTime(agentcashBackRecordRequest.getStartTime());
        couponProfitRecordDto.setEndTime(agentcashBackRecordRequest.getEndTime());
        PageInfo pageInfo = couponProfitRecordServiceApi.selectList(pager, couponProfitRecordDto);
        List<CouponProfitRecordDto> couponProfitRecordDtos = pageInfo.getList();
        if (!couponProfitRecordDtos.isEmpty() && couponProfitRecordDtos.size() > 0) {
            for (CouponProfitRecordDto couponProfitRecordDto1 : couponProfitRecordDtos) {
                AgentcashBackRecordResponse agentcashBackRecordResponse = new AgentcashBackRecordResponse();
                agentcashBackRecordResponse.setCreateTime(dateFormat(couponProfitRecordDto1.getIncomeTime()));
                agentcashBackRecordResponse.setDays(agentOrderYieldRatioDto.getCashbackTime());
                agentcashBackRecordResponse.setName(agentProtocolDto.getName());
                agentcashBackRecordResponse.setRemainingDays(agentOrderYieldRatioDto.getCashbackTime() - couponProfitRecordDtos.size());
                agentcashBackRecordResponse.setSubsidyAmount(agentOrderYieldRatioDto.getDailyIncome().multiply(new BigDecimal(agentOrderYieldRatioDto.getCashbackTime())));
                agentcashBackRecordResponse.setSubsidyToday(couponProfitRecordDto1.getAmount());
                agentcashBackRecordResponse.setTotalsubsidy(couponProfitRecordDto1.getAmount().multiply(new BigDecimal(couponProfitRecordDtos.size())));
                agentcashBackRecordResponse.setTotalsubsidySurplus(agentcashBackRecordResponse.getTotalsubsidy().subtract(agentcashBackRecordResponse.getTotalsubsidy()));
                list.add(agentcashBackRecordResponse);
            }
        }
        pageInfo.setList(list);
        return pageInfo;
    }

    public AgentProtocolAccountDtoResponse accountInformation(Long orderId) {
        AgentProtocolAccountDtoResponse agentProtocolAccountDtoResponse = new AgentProtocolAccountDtoResponse();
        AgentOrderInfoDto agentOrderInfoDto = agentOrderInfoServiceApi.queryOrderById(orderId);
        if (agentOrderInfoDto != null) {
            agentProtocolAccountDtoResponse.setStatus(agentOrderInfoDto.getStatus() + "");
            ProductUserDto productUserDto = productUserServiceApi.findById(agentOrderInfoDto.getMemberId());
            Ensure.that(productUserDto).isNotNull("01001505");
            DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
            MemberUserDto memberUserDto = memberUserServiceApi.findMemberByMobile(productUserDto.getPhone());
            Ensure.that(memberUserDto).isNotNull("01001505");
            DataSourceHolder.clearDataSource();
            MemberCouponsDto memberCouponsDto = memberCouponsServiceApi.findByMemberId(memberUserDto.getId());
            agentProtocolAccountDtoResponse.setOrderId(orderId);
            if (memberCouponsDto != null) {
                agentProtocolAccountDtoResponse.setLimitedMoney(memberCouponsDto.getLimitedMoney());
                agentProtocolAccountDtoResponse.setDragonMoney(memberCouponsDto.getDragonMoney());
                agentProtocolAccountDtoResponse.setAvailableMoney(memberCouponsDto.getAvailableMoney());
            } else {
                agentProtocolAccountDtoResponse.setLimitedMoney(BigDecimal.ZERO);
                agentProtocolAccountDtoResponse.setDragonMoney(BigDecimal.ZERO);
                agentProtocolAccountDtoResponse.setAvailableMoney(BigDecimal.ZERO);
            }
            AgentOrderYieldRatioDto agentOrderYieldRatioDto = agentOrderYieldRatioServiceApi.selectByOrderId(orderId);
            if (agentOrderYieldRatioDto != null) {
                agentProtocolAccountDtoResponse.setCashbackRatio(agentOrderYieldRatioDto.getCashbackRatio());
                agentProtocolAccountDtoResponse.setLimitTime(agentOrderYieldRatioDto.getLimitTime());
                agentProtocolAccountDtoResponse.setDailyIncome(agentOrderYieldRatioDto.getDailyIncome());
                agentProtocolAccountDtoResponse.setCashbackTime(agentOrderYieldRatioDto.getCashbackTime());
            }else {
                agentProtocolAccountDtoResponse.setCashbackRatio(BigDecimal.ZERO);
                agentProtocolAccountDtoResponse.setLimitTime(0);
                agentProtocolAccountDtoResponse.setDailyIncome(BigDecimal.ZERO);
                agentProtocolAccountDtoResponse.setCashbackTime(0);
            }
            List<AgentOrderProjectRecordDto> agentOrderProjectRecordDtos = agentOrderProjectRecordServiceApi.selectAgentOrderProjectRecordByOrderId(orderId);
            List<AgentProductProjectDto> agentProductProjectDtoList=new ArrayList<>();
            if (agentOrderProjectRecordDtos != null && agentOrderProjectRecordDtos.size() > 0) {
                for (AgentOrderProjectRecordDto agentOrderProjectRecordDto : agentOrderProjectRecordDtos) {
                    if (agentOrderProjectRecordDto!=null && agentOrderProjectRecordDto.getProjectId()!=null) {
                            AgentProductProjectDto agentProductProjectDto = new AgentProductProjectDto();
                            agentProductProjectDto.setContainNum(agentOrderProjectRecordDto.getCount());
                            ProjectDto projectDto = projectServiceApi.getById(agentOrderProjectRecordDto.getProjectId());
                            agentProductProjectDto.setName(projectDto.getName());
                            agentProductProjectDtoList.add(agentProductProjectDto);
                    }
                }
            }
            agentProtocolAccountDtoResponse.setAcountList(agentProductProjectDtoList);
            return agentProtocolAccountDtoResponse;
        }
        return null;
    }

        /**
         * 去除时间尾部.0
         *
         * @param date
         * @return
         */
    private String dateFormat(String date) {
        if (date.endsWith(".0")) {
            return date.substring(0, date.lastIndexOf("."));
        } else {
            return date;
        }
    }

    /**
     * 根据客户ID查询客户对应的合同
     */
    public AgentContractReponse queryContractByOrderId(Long orderId) {
        AgentContractReponse agentContractReponse = new AgentContractReponse();
        AgentOrderInfoDto agentOrderInfoDto = agentOrderInfoServiceApi.queryContractByOrderId(orderId);
        Ensure.that(agentOrderInfoDto).isNotNull("01001615");
        agentContractReponse.setSignedPhoto(agentOrderInfoDto.getSignedPhoto());
        agentContractReponse.setOrderId(agentOrderInfoDto.getOrderId());
        agentContractReponse.setContractUrl(agentOrderInfoDto.getContractUrl());
        agentContractReponse.setCreateTime(agentOrderInfoDto.getCreateTime());
        agentContractReponse.setIdCard(agentOrderInfoDto.getIdCard());
        agentContractReponse.setName(agentOrderInfoDto.getName());
        agentContractReponse.setContractName(agentOrderInfoDto.getContractName());
        return agentContractReponse;
    }
}
